package com.violet.service.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.violet.domain.dto.manager.MAdminDto;
import com.violet.domain.exceptions.DTOVerifyException;
import com.violet.domain.po.Admin;
import com.violet.domain.vo.manager.AdminVo;
import com.violet.mapper.AdminMapper;
import com.violet.service.manager.MLoginService;
import com.violet.utils.JwtTokenUtil;
import com.violet.utils.TransitionUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class MLoginServiceImpl extends ServiceImpl<AdminMapper, Admin>
        implements MLoginService {

    private final BCryptPasswordEncoder passwordEncoder;
    private final TransitionUtils<MAdminDto, Admin, AdminVo> transition;

    @Override
    public AdminVo login(MAdminDto dto) {
        Admin admin = baseMapper.selectOne(new LambdaQueryWrapper<Admin>().eq(Admin::getName, dto.getName()));
        if (admin == null) throw new DTOVerifyException("", "用户名或密码错误");
        if (passwordEncoder.matches(dto.getPassword(), admin.getPassword())) {
            // 生成 token
            String token = JwtTokenUtil.generateToken(admin.getName());
            // 设置最后登录时间
            admin.setLastLoginTime(LocalDateTime.now());
            baseMapper.update(admin, new LambdaUpdateWrapper<Admin>().eq(Admin::getName, admin.getName()));
            // 转换成 VO, 返回
            return transition.transition(admin, AdminVo.class).setToken(token);
        }
        throw new DTOVerifyException("", "用户名或密码错误");
    }
}
